<template>
  <div id="mapBody">
    <!-- 左上 -->
    <div class="left-top">
      <div class="cursor-pointer">
        <el-tooltip
          class="item"
          effect="dark"
          :content="$t('重定位')"
          placement="left"
        >
          <img
            v-if="relocateFlag"
            src="../../assets/images/home/mapLedtTwo.png"
            @click="relocatBtn"
            alt=""
          />
          <img
            @click="relocatTwo"
            v-else
            src="../../assets/images/home/blueSpot.png"
          />
        </el-tooltip>
      </div>
      <!-- 导入背景图 -->
      <div
        style="border-top: 1px solid rgba(241, 243, 249, 0.2)"
        class="cursor-pointer"
      >
        <el-popover
          popper-class="newheel-setBg"
          placement="right-start"
          width="260"
          v-model="visible"
          trigger="click"
        >
          <div class="bgImgDiv">
            <!-- 头部操作按钮 -->
            <div class="bgHeader">
              <span style="color: #ffff">导入背景图</span>
              <div class="actionImg">
                <img
                  @click="exportBg"
                  style="margin-right: 8px; cursor: pointer"
                  src="../../assets/images/home/exportBg.png"
                  title="导出背景图"
                />
                <img
                  @click="deleteBg"
                  style="margin-right: 8px; cursor: pointer"
                  src="../../assets/images/home/deleteBg.png"
                  title="删除背景图"
                />
                <img
                  style="cursor: pointer"
                  @click="closeBg"
                  src="../../assets/images/home/closeSetbg.png"
                  title="关闭"
                />
              </div>
            </div>
            <!-- 操作步骤 -->
            <div class="bgContent">
              <div>
                <img
                  style="margin-right: 8px; vertical-align: middle"
                  src="../../assets/images/home/set-one.png"
                />
                <div style="display: inline-block">
                  <span style="color: #ffffff">导出地图</span>
                  <span @click="exportMap" class="actionButton"> 导出 </span>
                </div>
                <div class="tipsDiv">
                  <span class="tip-grey">用于绘制背景图，</span
                  ><span class="tip-red">不可修改尺寸和位置</span>
                </div>
              </div>
              <div style="margin-top: 20px; position: relative">
                <img
                  style="margin-right: 8px; vertical-align: text-bottom"
                  src="../../assets/images/home/set-two.png"
                />
                <div style="display: inline-block; color: #ffffff">
                  选择背景图
                </div>
                <div class="tipsDiv">
                  <span class="tip-grey">支持jpg、jpeg、png,≤5M</span>
                </div>
                <input
                  accept=".jpg,.jpeg,.png"
                  style="margin: 8px 0; width: 100px"
                  type="file"
                  @click="
                    (e) => {
                      e.target.value = '';
                    }
                  "
                  @change="changeImage($event)"
                  id="file1"
                  name="file1"
                />
                <span class="imgTitle" id="imgTitle"></span>
                <img id="img1" src="" />
              </div>
              <div style="margin-top: 14px">
                <!-- <el-collapse accordion> -->
                <!-- <el-collapse-item title="高级设置"> -->
                <img
                  style="margin-right: 8px; vertical-align: text-bottom"
                  src="../../assets/images/home/set-three.png"
                />
                <div style="display: inline-block">
                  <span style="color: #ffffff">设置</span
                  ><span style="color: #ff4c5e">背景图</span
                  ><span style="color: #ff4c5e">左下角</span
                  ><span style="color: #ffffff">位置</span>
                  <span @click="pickupPos" class="actionButton">拾取</span>
                </div>
                <div style="margin-top: 8px">
                  <span class="tip-grey"
                    >在地图上拾取一个点,作为背景图左下角位置</span
                  >
                </div>
                <div style="display: inline-block; margin-top: 6px">
                  <div style="display: inline-block; margin-left: 8px">
                    <span class="tip-grey">X: </span
                    ><el-input-number
                      :step="0.01"
                      :precision="2"
                      controls-position="right"
                      class="setCoordinate"
                      style="width: 85px; margin-bottom: 8px"
                      v-model="form.x"
                    ></el-input-number>
                  </div>
                  <div style="display: inline-block; margin-left: 27px">
                    <span class="tip-grey">Y: </span
                    ><el-input-number
                      :step="0.01"
                      class="setCoordinate"
                      style="width: 85px"
                      v-model="form.y"
                    ></el-input-number>
                  </div>
                </div>
                <!-- <div style="display: inline-block">
                  <img
                    style="vertical-align: bottom"
                    src="../../assets/images/home/coordinate.png"
                    alt=""
                  />
                </div> -->
                <div style="margin-top: 2px">
                  <img
                    style="margin-right: 8px; vertical-align: text-bottom"
                    src="../../assets/images/home/set-four.png"
                  />
                  <span
                    style="
                      display: inline-block;
                      color: #ffffff;
                      margin-right: 8px;
                    "
                    >缩放比例</span
                  >
                  <el-input-number
                    class="setCoordinate"
                    style="width: 128px; margin-right: 4px"
                    v-model="form.scale"
                  ></el-input-number>
                  <span class="tip-grey">%</span>
                </div>
                <!-- </el-collapse-item>
                </el-collapse> -->
              </div>
              <div
                style="
                  margin-top: 12px;
                  border-top: 1px dashed #33414c;
                  padding: 12px 0 0 24px;
                "
              >
                <div
                  class="status-btn cursor-pointer"
                  style="margin-right: 14px"
                  @click="previewBg"
                >
                  {{ $t("预览") }}
                </div>
                <div class="status-btn cursor-pointer" @click="saveBg">
                  {{ $t("保存") }}
                </div>
              </div>
            </div>
          </div>
          <img
            :title="$t('导入背景图')"
            slot="reference"
            src="../../assets/images/home/importBg-grey.png"
          />
        </el-popover>
      </div>
    </div>
    <!-- 左下 -->
    <div class="left-bottom">
      <div class="two cursor-pointer">
        <el-tooltip
          class="item"
          effect="dark"
          :content="$t('导航置信度')"
          placement="left"
        >
          <img :src="matchDegreeUrl" alt="" />
        </el-tooltip>
        <span>{{ matchDegree || 0 }}%</span>
      </div>
    </div>
    <RobotData
      :moveMotor="moveMotor"
      :robotPositionInfo="robotPositionInfo"
      :isShowSJB="isShowSJB"
      :cameraInfo="cameraInfo"
    ></RobotData>
    <!-- 右上 -->
    <div class="right-top">
      <el-checkbox-group v-model="checkedLists" @change="checkboxChang">
        <el-checkbox
          v-for="(item, index) in checklist"
          :key="index"
          :label="item.label"
        >
          <img class="right-top-img" :src="item.img" alt="" />
          <span class="mar-l-5">{{ item.title }}</span>
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <!-- 右下 -->
    <div class="right-bottom">
      <div class="two cursor-pointer">
        <el-tooltip
          class="item"
          effect="dark"
          :content="$t('地图复位')"
          placement="top"
        >
          <img
            @click="mapReset"
            src="../../assets/images/home/fuwei.png"
            alt=""
          />
        </el-tooltip>
      </div>
    </div>
    <!-- 机器人点 -->
    <div id="robotPos" class="robotPos">
      <img
        style="width: 24px; height: 24px"
        src="../../assets/images/home/robot.png"
      />
    </div>
    <div
      :class="pickFlag ? 'pickup-cursor' : 'pickup-default'"
      style="height: 500px; width: 100%; background-color: inherit"
      id="map"
      class="map"
    ></div>
  </div>
</template>

<script>
import {
  API_mapInfo,
  API_relocate,
  API_robotSetting, //机器人控制
  API_positionInfo, //导航置信度
  API_robotMove, //机器人控制
  API_getRobotRunMode, //机器人任务模式
  API_batteryInfo, //电池电量
  API_updateBg,
} from "@/api/robot/monitor";
import { Map, View } from "ol";
import "ol/ol.css";
import WebGLPointsLayer from "ol/layer/WebGLPoints";
import Feature from "ol/Feature";
import Overlay from "ol/Overlay.js";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource, ImageStatic } from "ol/source";
import Point from "ol/geom/Point";
import { Polygon } from "ol/geom";
import LineString from "ol/geom/LineString";
import Projection from "ol/proj/Projection";
import { Fill, Style, Stroke } from "ol/style";
import { Image as ImageBg } from "ol/layer.js";
import ImageLayer from "ol/layer/Image";
import Static from "ol/source/ImageStatic";
import { getCenter } from "ol/extent";
import AvatarUpload from "@/components/AvatarUpload";
import $ from "jquery";
import { getToken } from "@/utils/auth";
import domtoimage from "dom-to-image";
import FileSaver from "file-saver";
import {
  defaults as defaultControls,
  FullScreen,
  ZoomSlider,
} from "ol/control";
import RobotData from "../RobotData.vue";

export default {
  components: {
    AvatarUpload,
    RobotData,
  },
  props: {
    moveMotor: {
      type: String,
      default: "1",
    },
    robotPositionInfo: {
      type: Object,
      default: () => {},
    },
    isShowSJB: {
      type: Boolean,
      default: false,
    },
    cameraInfo: {
      type: Object,
      default: () => {},
    },
    gdType: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      map: null,
      mapParam: {}, //地图的参数
      robotType: "1",
      initSmapNormalPoint: false,
      vectorLayer: "",
      vectorSource: "",
      time: "",
      marker: null, //移动点
      commonPoints: [], //普通点
      sitePoints: [], //站点位置
      cdzPoints: [], //充电桩位置
      robotPosition: [], //机器人位置
      inspectionPoints: [], //巡检点
      startPoint: {}, //起点
      endPoint: {}, //终点
      checkedLists: ["1", "3", "4", "5", "6"], //复选框 被选中数据
      isRelocat: false, //是否重定位
      isScreenFull: false, //是否全屏
      startPoint: {}, //起点
      endPoint: {}, //终点
      startX: "", //按下 x点
      startY: "", //按下 y点
      endX: "", //弹起 x点
      endY: "", //弹起 y点
      pluseScaleNums: 0, //放大缩小次数
      scalePlusPersent: 100, //缩放比例
      value: [],
      mapBody: "",
      WebGLPointsLayer: "", //地图图层
      matchDegree: "", //导航置信度
      runmodelTimer: null, //机器人模式定时器
      ZDUrl: require("../../assets/images/home/zhandian.png"),
      AIUrl: require("../../assets/images/home/AI.png"),
      RFIDUrl: require("../../assets/images/home/RFID.png"),
      CDZUrl: require("../../assets/images/home/CDZ.png"),
      robotUrl: require("../../assets/images/home/robot.png"),
      matchDegreeUrl: require("../../assets/images/home/red.png"), //置信度图片
      mapBgUrl: require("../../assets/home/mapBg.png"), //背景图片
      markerInspect: null, //巡检点
      markerCdz: null, //充电桩
      markerSite: null, //站点
      siteBool: true,
      inspectionBool: true,
      changeBool: true,
      robotBool: true,
      advancedCurveList: [],
      advancedPointList: [],
      isChoosenMode: "", //机器模式
      mapPoints: [], //重定位点
      relocateFlag: true,
      maxPos: "",
      minPos: "",
      isShowImg: false, //是否在充电
      bateryTimer: "",
      defaultFile: ["jpg", "jpeg", "png"], //默认图片类型
      form: {
        y: -35,
        x: -185,
        scale: 100,
        backgroundUrl: "",
      },
      imgInfo: {},
      layers: "",
      visible: false,
      mapBgId: "",
      mapBgInfo: {},
      openFlag: true, //图标展开收起
      closeFlag: true,
      textInfo: true,
      pickFlag: false, //是否正在选取左下角坐标
      saveFlag: false,
    };
  },
  watch: {
    siteBool(newVal) {
      if (newVal) {
        this.showPoint("1", "sitePoints");
      } else {
        this.showPoint("0", "sitePoints");
      }
    },
    inspectionBool(newVal) {
      if (newVal) {
        this.showPoint("1", "inspection");
      } else {
        this.showPoint("0", "inspection");
      }
    },
    changeBool(newVal) {
      if (newVal) {
        this.showPoint("1", "cdzPoints");
      } else {
        this.showPoint("0", "cdzPoints");
      }
    },
    robotBool(newVal) {
      if (newVal) {
        this.time = setInterval(() => {
          this.getRobotPosition(); //机器人位置信息
          this.marker.setPosition([
            this.robotPosition[0].x,
            this.robotPosition[0].y,
          ]);
        }, 1000);
      } else {
        clearInterval(this.time);
        this.marker.setPosition(undefined);
      }
    },
  },
  computed: {
    isCanController(val) {
      return this.isChoosenMode == "0" ? true : false;
    },
    checklist(val) {
      if (this.gdType) {
        return [
          {
            label: "2",
            img: require("../../assets/images/home/lujing.png"),
            title: this.$t("路径"),
          },
          {
            label: "4",
            img: require("../../assets/images/home/AI.png"),
            title: this.$t("巡检点"),
          },
          {
            label: "5",
            img: require("../../assets/images/home/CDZ.png"),
            title: this.$t("充电桩"),
          },
          {
            label: "7",
            img: require("../../assets/images/home/RFID.png"),
            title: "RFID",
          },
          {
            label: "6",
            img: require("../../assets/images/home/robot.png"),
            title: this.$t("机器人"),
          },
        ];
      } else {
        return [
          {
            label: "2",
            img: require("../../assets/images/home/lujing.png"),
            title: this.$t("路径"),
          },
          {
            label: "4",
            img: require("../../assets/images/home/AI.png"),
            title: this.$t("巡检点"),
          },
          {
            label: "7",
            img: require("../../assets/images/home/RFID.png"),
            title: "RFID",
          },
          {
            label: "6",
            img: require("../../assets/images/home/robot.png"),
            title: this.$t("机器人"),
          },
        ];
      }
    },
  },
  mounted() {
    let robotPos = document.getElementById("robotPos");
    robotPos.style.display = "none";
    this.getRobotRunModel(); //获取机器人任务模式
    this.getMatchDegree();
    this.initMap();
    this.runmodelTimer = setInterval(() => {
      this.getRobotRunModel();
      this.getMatchDegree(); //导航置信度
    }, 1000);
    this.bateryTimer = setInterval(() => {
      this.getBateryInfo();
    }, 10000);
  },
  methods: {
    //关闭背景图设置 没有保存时恢复到初始状态
    closeBg() {
      if (!this.saveFlag) {
        if (this.mapBgInfo && this.mapBgInfo.backgroundUrl) {
          this.form = {
            y: Number(this.mapBgInfo.y),
            x: Number(this.mapBgInfo.x),
            scale: Number(this.mapBgInfo.scale),
            backgroundUrl: this.mapBgInfo.backgroundUrl,
          };
          let arr = [];
          let str = "";
          let imgName = "";
          arr = this.mapBgInfo.backgroundUrl.split("/");
          str = arr[arr.length - 1];
          imgName = str.slice(13, str.length);
          document.getElementById("imgTitle").innerHTML = imgName;
          this.imgInfo.width = this.mapBgInfo.width;
          this.imgInfo.height = this.mapBgInfo.height;
          this.previewBg();
        } else {
          this.form = {
            y: "",
            x: "",
            scale: 100,
            backgroundUrl: "",
          };
          document.getElementById("imgTitle").innerHTML = "";
          this.map.removeLayer(this.layers); //移除背景图
        }
      }
      this.visible = false;
    },
    //选取左下角坐标
    pickupPos() {
      if (!this.form.backgroundUrl) {
        this.$message({
          message: this.$t("请先选择背景图"),
          type: "warning",
        });
        return false;
      }
      this.pickFlag = true;
      this.visible = false;
      this.map.on("singleclick", (e) => {
        this.form.x = e.coordinate[0].toFixed(2);
        this.form.y = e.coordinate[1].toFixed(2);
        this.visible = true;
        this.pickFlag = false;
      });
    },
    closeInfo() {
      this.closeFlag = !this.closeFlag;
      var ele = document.querySelector(".positionInfo");
      ele.classList.remove("openInfo");
      ele.classList.add("closeInfo");
      //动画结束后隐藏文字信息
      setTimeout(() => {
        this.textInfo = false;
      }, 500);
    },
    openInfo() {
      this.closeFlag = !this.closeFlag;
      var ele = document.querySelector(".positionInfo");
      ele.classList.remove("closeInfo");
      ele.classList.add("openInfo");
      this.textInfo = true;
    },
    closeIcon() {
      this.openFlag = !this.openFlag;
      var ele = document.querySelector(".right-top");
      ele.classList.remove("open");
      ele.classList.add("close");
    },
    openIcon() {
      this.openFlag = !this.openFlag;
      var ele = document.querySelector(".right-top");
      ele.classList.remove("close");
      ele.classList.add("open");
    },
    exportMap() {
      let that = this;
      that.map.removeLayer(this.layers); //移除背景图
      let leftTop = document.getElementsByClassName("left-top")[0];
      let rightTop = document.getElementsByClassName("right-top")[0];
      let rightBottom = document.getElementsByClassName("right-bottom")[0];
      let olFullScreen = document.getElementsByClassName("ol-full-screen")[0];
      let leftBottom = document.getElementsByClassName("left-bottom")[0];
      leftTop.style.display = "none";
      rightTop.style.display = "none";
      rightBottom.style.display = "none";
      olFullScreen.style.display = "none";
      leftBottom.style.display = "none";
      this.visible = false;
      setTimeout(() => {
        let node = document.getElementsByClassName("map")[0];
        domtoimage
          .toPng(node, {
            bgcolor: "#00111F",
          })
          .then(function (dataUrl) {
            FileSaver.saveAs(dataUrl, "map.png");
            leftTop.style.display = "flex";
            rightTop.style.display = "block";
            rightBottom.style.display = "flex";
            leftBottom.style.display = "flex";
            olFullScreen.style.display = "block";
            this.visible = true;
            that.map.addLayer(that.layers); //添加背景图
          })
          .catch(function (error) {
            console.error("生成失败", error);
          });
      }, 1000);
    },
    exportBg() {
      if (!this.form.backgroundUrl) {
        this.$message({
          message: this.$t("请先选择背景图"),
          type: "warning",
        });
        return false;
      }
      this.$download.resource(this.form.backgroundUrl);
    },
    previewBg() {
      this.map.removeLayer(this.layers);
      this.layers = "";
      // var mapExtent = this.map.getView().calculateExtent(this.map.getSize());
      const mapExtent = [
        Number(this.form.x),
        Number(this.form.y),
        (this.imgInfo.width * this.form.scale) / 1000 + Number(this.form.x),
        (this.imgInfo.height * this.form.scale) / 1000 + Number(this.form.y),
      ];
      const extent = mapExtent;
      let projection = new Projection({
        //定义坐标系
        code: "xkcd-image",
        units: "pixels",
        extent: extent,
      });
      this.layers = new ImageBg({
        source: new ImageStatic({
          // 创建一个图像图层
          url:
            window.location.protocol +
            "//" +
            window.location.host +
            this.form.backgroundUrl,
          // url: 'http://192.168.61.11' + this.form.backgroundUrl,
          // url: `http://172.17.10.242:8888/${this.form.backgroundUrl}`,,
          projection: projection,
          imageExtent: extent,
        }),
      });
      this.map.addLayer(this.layers);
    },
    saveBg() {
      if (!this.form.backgroundUrl) {
        this.$message({
          message: this.$t("请先选择背景图"),
          type: "warning",
        });
        return false;
      }
      let params = {
        id: this.mapBgId,
        x: this.form.x,
        y: this.form.y,
        scale: this.form.scale,
        backgroundUrl: this.form.backgroundUrl,
        width: this.imgInfo.width,
        height: this.imgInfo.height,
      };
      API_updateBg(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: this.$t("保存成功"),
            type: "success",
          });
          this.saveFlag = true;
          this.visible = false;
          this.previewBg();
        }
      });
    },
    deleteBg() {
      if (!this.form.backgroundUrl) {
        this.$message({
          message: this.$t("请先选择背景图"),
          type: "warning",
        });
        return false;
      }
      this.form = {
        y: "",
        x: "",
        scale: 100,
        backgroundUrl: "",
      };
      this.form.id = this.mapBgId;
      document.getElementById("img1").src = "";
      API_updateBg(this.form).then((res) => {
        if (res.code == 200) {
          this.map.removeLayer(this.layers);
          this.$message({
            message: this.$t("删除成功"),
            type: "success",
          });
          document.getElementById("imgTitle").innerHTML = "";
          //清空上传的文件
          // var _file = document.getElementById("file1");
          // _file.outerHTML = _file.outerHTML;
        }
      });
    },
    changeImage(e) {
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: this.$t("上传的文件格式不正确！"),
          type: "warning",
        });
        return false;
      }
      if (e.target.files[0].size > 5 * 1024 * 1024) {
        this.$message({
          message: this.$t("上传的文件大小不能超过5M！"),
          type: "warning",
        });
        return false;
      }
      let that = this;
      //创建文件读取对象
      let reader = new FileReader();
      let fil = document.getElementById("file1").files;
      let sendData = new FormData();
      sendData.append("file", fil[0]);
      $.ajax({
        type: "POST", // 规定请求的类型（GET 或 POST）
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        url: process.env.VUE_APP_BASE_API + "/news/upload/2", // 请求的url地址(线上的加上/)
        dataType: "json", //预期的服务器响应的数据类型
        contentType: false,
        processData: false, //不处理发送的数据
        data: sendData,
        success: function (res) {
          // 当请求成功时运行的函数
          that.form.backgroundUrl = res.data[0].path;
          //获取图片原始宽高
          reader.readAsDataURL(fil[0]);
          reader.onload = function () {
            document.getElementById("img1").src = reader.result;
            let base64 = document.getElementById("img1").src;
            let img = new Image();
            img.src = base64;
            let arr = [];
            let str = "";
            let imgName = "";
            arr = that.form.backgroundUrl.split("/");
            str = arr[arr.length - 1];
            imgName = str.slice(13, str.length);
            document.getElementById("imgTitle").innerHTML = imgName;
            document.getElementById("img1").style.display = "none";
            // document.getElementById("img1").style.width = "60px";
            // document.getElementById("img1").style.height = "40px";
            //获取图片的原始宽高
            img.onload = function () {
              that.imgInfo.width = img.naturalWidth;
              that.imgInfo.height = img.naturalHeight;
              that.imgInfo.src = fil[0].path;
            };
          };
        },
        error: function (err) {
          //失败的函数
        },
      });
    },
    /**电池电量 */
    getBateryInfo() {
      API_batteryInfo().then((res) => {
        if (res.code == 200) {
          if (res.data.batteryStatus !== null) {
            let info = JSON.parse(res.data.batteryStatus);
            //充电状态
            if (info.current > 0) {
              this.isShowImg = true;
            } else {
              this.isShowImg = false;
            }
          }
        }
      });
    },
    /**导航置信度 */
    getMatchDegree() {
      API_positionInfo().then((res) => {
        if (res.code == 200 && res.data) {
          this.matchDegree = JSON.parse(res.data).matchDegree;
          if (this.matchDegree >= 0 && this.matchDegree <= 25) {
            this.matchDegreeUrl = require("../../assets/images/home/red.png");
          } else if (this.matchDegree >= 26 && this.matchDegree <= 60) {
            this.matchDegreeUrl = require("../../assets/images/home/origin.png");
          } else {
            this.matchDegreeUrl = require("../../assets/images/home/green.png");
          }
        }
      });
    },
    /**地图复位 */
    mapReset() {
      this.smapAdaptive(this.maxPos, this.minPos); //自适应缩放比例
    },
    /**获取机器人操作模式 */
    getRobotRunModel() {
      API_getRobotRunMode().then((res) => {
        if (res.code == 200 && res.data) {
          this.isChoosenMode = res.data.parameterValue;
        }
      });
    },
    //第二次点击重定位
    relocatTwo() {
      this.relocateFlag = !this.relocateFlag;
      if (this.mapPoints.length == 0 || this.mapPoints.length < 4) {
        this.$message.info(
          this.$t("请在地图上选择两个点后再次点击重定位进行重定位操作")
        );
        return;
      }
      if (this.mapPoints.length > 4) {
        this.mapPoints = this.mapPoints.slice(0, 4);
      }
      let params = {
        cmd: "2X62",
        values: this.mapPoints,
      };
      API_relocate(params)
        .then((res) => {
          if (res.code == 200 && res.data.nerrcode == 0) {
            this.$message.success(this.$t("重定位成功"));
          } else {
            this.$message.error(this.$t("重定位失败"));
          }
        })
        .finally(() => {
          this.mapPoints = [];
          this.isRelocat = false;
        });
    },
    //第一次点击重定位
    relocatBtn() {
      if (this.isChoosenMode == "0") {
        this.$message({
          message: this.$t("任务模式无法操作重定位动作"),
          type: "warning",
        });
        return false;
      }
      this.relocateFlag = !this.relocateFlag;
      this.isRelocat = true;
      //监听地图点击事件
      this.map.on("click", (e) => {
        if (this.isRelocat) {
          this.mapPoints.push(e.coordinate[0], e.coordinate[1]);
        }
      });
    },
    //获取机器人位置信息
    async getRobotPosition() {
      await API_positionInfo().then((res) => {
        if (res.code == 200 && res.data) {
          this.robotPosition = [
            {
              x: JSON.parse(res.data).carX / 1000,
              y: JSON.parse(res.data).carY / 1000,
            },
          ];
        }
      });
    },
    async initMap() {
      await this.getRobotPosition();
      const extent = [-20026376.39, -20048966.1, 20026376.39, 20048966.1]; //图片图层四至
      let projection = new Projection({
        code: "EPSG:3857",
        units: "pixels",
        extent: extent,
      });
      this.map = new Map({
        target: "map",
        view: new View({
          center: [0, 0],
          zoom: 2, //地图比例
          maxZoom: 26,
          minZoom: 2,
          projection: projection,
          constrainResolution: true, // 设置缩放级别为整数
          smoothResolutionConstraint: true, // 关闭无级缩放地图
        }),
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false,
        }).extend([new FullScreen()]),
      });
      // 创建图层
      this.vectorLayer = new VectorLayer();
      // 创建数据容器
      this.vectorSource = new VectorSource();
      // 把数据容器添加到图层
      this.vectorLayer.setSource(this.vectorSource);
      this.getPoints();
      this.map.addLayer(this.vectorLayer);
      this.map.on("singleclick", (evt) => {
        console.log(evt.coordinate);
      });
    },
    //添加普通点
    smapNormalPoint() {
      let style = {
        symbol: {
          symbolType: "image",
          size: 3,
          color: "#f2bb18",
        },
      };
      let features = [];
      this.commonPoints.forEach((item) => {
        let lon = item.x;
        let lat = item.y;
        let feature = new Feature({
          geometry: new Point([lon, lat]),
        });
        features.push(feature);
      });
      let vectorSource = new VectorSource({
        features: features,
      });
      this.WebGLPointsLayer = new WebGLPointsLayer({
        source: vectorSource,
        style: style,
        className: "normalPoints",
      });
      this.map.addLayer(this.WebGLPointsLayer);
    },
    initRobot() {
      var markerEl = document.getElementById("robotPos");
      this.marker = new Overlay({
        position: [this.robotPosition[0].x, this.robotPosition[0].y],
        positioning: "center-center",
        offset: [0, 0],
        element: markerEl,
        stopEvent: false,
      });
      this.map.addOverlay(this.marker);
      markerEl.style.display = "block";
      this.time = setInterval(() => {
        this.getRobotPosition(); //机器人位置信息
        this.marker.setPosition([
          this.robotPosition[0].x,
          this.robotPosition[0].y,
        ]);
      }, 1000);
    },
    //添加巡检点
    addInspection() {
      let mapBody = document.getElementById("mapBody");
      this.inspectionPoints.forEach((item, index) => {
        let div = document.createElement("div");
        div.id = `inspection${index}`;
        let img = document.createElement("img");
        img.style.width = "24px";
        img.style.height = "24px";
        img.src = this.AIUrl;
        img.title = item.name;
        div.appendChild(img);
        mapBody.insertBefore(div, mapBody.childNodes[1]);

        this.markerInspect = new Overlay({
          position: [item.x, item.y],
          positioning: "center-center",
          offset: [0, 0],
          element: document.getElementById(`inspection${index}`),
          stopEvent: false,
        });
        this.map.addOverlay(this.markerInspect);
        let title = item.title;
        let ele = document.getElementById(`inspection${index}`);
        this.removeRobot(ele, title);
      });
    },
    //移动机器人
    removeRobot(ele, title) {
      ele.onclick = () => {
        if (this.pickFlag || this.isRelocat) {
          return;
        } else if (this.isCanController) {
          this.$message.warning(this.$t("任务模式下无法操作GoTo命令"));
          return;
        } else {
          this.$confirm(this.$t("确定将机器人移动至此位置"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          })
            .then(() => {
              API_robotMove({
                cmd: "1X37",
                values: [title],
              }).then((res) => {
                if (res.code == 200 && res.data.nerrcode == 0) {
                  this.$message.success(this.$t("操控成功"));
                } else {
                  this.$message.error(this.$t("操作失败请重试"));
                }
              });
            })
            .catch(() => {
              this.$message.info(this.$t("已取消"));
            });
        }
      };
    },
    //添加充电桩
    addCharge() {
      let mapBody = document.getElementById("mapBody");
      this.cdzPoints.forEach((item, index) => {
        let div = document.createElement("div");
        div.id = `cdzPoints${index}`;
        let img = document.createElement("img");
        img.style.width = "24px";
        img.style.height = "24px";
        img.src = this.CDZUrl;
        img.title = item.title;
        div.appendChild(img);
        mapBody.insertBefore(div, mapBody.childNodes[1]);

        this.markerCdz = new Overlay({
          position: [item.x, item.y],
          positioning: "center-center",
          offset: [0, 0],
          element: document.getElementById(`cdzPoints${index}`),
          stopEvent: false,
        });
        this.map.addOverlay(this.markerCdz);

        let title = item.title;
        let ele = document.getElementById(`cdzPoints${index}`);
        this.removeRobot(ele, title);
      });
    },
    //添加站点
    addSite() {
      let mapBody = document.getElementById("mapBody");
      this.sitePoints.forEach((item, index) => {
        let div = document.createElement("div");
        div.id = `sitePoints${index}`;
        let img = document.createElement("img");
        img.style.width = "24px";
        img.style.height = "24px";
        img.src = this.ZDUrl;
        img.title = item.title;
        div.appendChild(img);
        mapBody.insertBefore(div, mapBody.childNodes[1]);

        this.markerSite = new Overlay({
          position: [item.x, item.y],
          positioning: "center-center",
          offset: [0, 0],
          element: document.getElementById(`sitePoints${index}`),
          stopEvent: false,
        });
        this.map.addOverlay(this.markerSite);
        let title = item.title;
        let ele = document.getElementById(`sitePoints${index}`);
        this.removeRobot(ele, title);
      });
    },
    getPoints() {
      API_mapInfo().then((res) => {
        this.mapBgInfo = res.data.map;
        if (this.mapBgInfo.backgroundUrl) {
          this.saveFlag = false;
          document.getElementById("img1").src =
            window.location.protocol +
            "//" +
            window.location.host +
            this.mapBgInfo.backgroundUrl;
          document.getElementById("img1").style.display = "none";
          // document.getElementById("img1").style.width = "60px";
          // document.getElementById("img1").style.height = "40px";
          this.form = {
            y: Number(this.mapBgInfo.y),
            x: Number(this.mapBgInfo.x),
            scale: Number(this.mapBgInfo.scale),
            backgroundUrl: this.mapBgInfo.backgroundUrl,
          };
          let arr = [];
          let str = "";
          let imgName = "";
          arr = this.mapBgInfo.backgroundUrl.split("/");
          str = arr[arr.length - 1];
          imgName = str.slice(13, str.length);
          document.getElementById("imgTitle").innerHTML = imgName;
          this.imgInfo.width = res.data.map.width;
          this.imgInfo.height = res.data.map.height;
          this.previewBg();
        }
        this.mapBgId = this.mapBgInfo.id;
        this.advancedCurveList = res.data.mapInfo.advancedCurveList;
        //普通点数据
        this.commonPoints =
          res.data.smap.normalPosList.length > 0
            ? res.data.smap.normalPosList
            : [];
        let viewPoints = res.data.viewPoints; //巡检点
        let cdzPoints = res.data.chargePiles; //充电桩
        viewPoints = viewPoints.map((item) => item.locationPos); //只取locationPos项
        cdzPoints = cdzPoints.map((item) => item.instanceName);
        this.advancedPointList =
          res.data.mapInfo.advancedPointList.length > 0
            ? res.data.mapInfo.advancedPointList
            : [];
        // 巡检点
        this.inspectionPoints = this.advancedPointList.filter((item) =>
          viewPoints.includes(item.instanceName)
        );
        this.inspectionPoints.forEach((item) => {
          res.data.viewPoints.forEach((ele) => {
            if (item.instanceName === ele.locationPos) {
              item.name = ele.viewPointName;
            }
          });
        });
        // 站点
        this.sitePoints = this.advancedPointList.filter(
          (item) => !viewPoints.includes(item.instanceName)
        );
        // 充电桩
        this.cdzPoints = this.advancedPointList.filter((item) =>
          cdzPoints.includes(item.instanceName)
        );
        //巡检点 放大
        this.inspectionPoints = this.inspectionPoints.map((item) => {
          return {
            x: item.pos.x,
            y: item.pos.y,
            title: item.instanceName,
            name: item.name,
          };
        });
        //站点 放大
        this.sitePoints = this.sitePoints.map((item) => {
          return {
            x: item.pos.x,
            y: item.pos.y,
            title: item.instanceName,
          };
        });
        //充电桩 放大
        this.cdzPoints = this.cdzPoints.map((item) => {
          return {
            x: item.pos.x,
            y: item.pos.y,
            title: item.instanceName,
          };
        });
        this.maxPos = res.data.smap.header.maxPos;
        this.minPos = res.data.smap.header.minPos;
        this.smapNormalPoint(); //添加普通点
        this.smapAdaptive(this.maxPos, this.minPos); //自适应缩放比例
        this.initRobot(); //添加机器人点
        this.addInspection(); //添加巡检点
        this.addCharge(); //添加充电桩
        this.addSite(); //添加站点
        this.getLineData(); //添加线
      });
    },
    //自适应地图大小
    smapAdaptive(maxPos, minPos) {
      const p1 = [minPos.x, minPos.y];
      const p2 = [maxPos.x, minPos.y];
      const p3 = [maxPos.x, maxPos.y];
      const p4 = [minPos.x, maxPos.y];
      const coor_bigger_box = [p1, p2, p3, p4];
      let shape_tmp = new Feature({
        geometry: new Polygon([coor_bigger_box]),
      });
      let tmpLayer = new VectorLayer({
        className: "Adaptive",
        source: new VectorSource(),
        style: new Style({
          stroke: new Stroke({
            color: "rgba(0,0,0,0)",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(0,0,0,0)",
          }),
        }),
      });
      tmpLayer.getSource().addFeature(shape_tmp);
      let feature = tmpLayer.getSource().getFeatures()[0];
      let autoPolygon = feature.getGeometry();
      this.map.getView().fit(autoPolygon, this.map.getSize(), {
        padding: [0, 0, 0, 0],
        constrainResolution: false,
      });
    },
    /**获取点数据 */
    getLineData() {
      let startPoint = {};
      let endPoint = {};
      for (var i = 0; i < this.advancedCurveList.length; i++) {
        startPoint = this.advancedPointList.find((pointItem) => {
          return (
            pointItem.instanceName ==
            this.advancedCurveList[i].startPos.instanceName
          );
        });
        endPoint = this.advancedPointList.find((pointItem) => {
          return (
            pointItem.instanceName ==
            this.advancedCurveList[i].endPos.instanceName
          );
        });
        //线 放大
        this.startPoint.x = startPoint.pos.x;
        this.startPoint.y = startPoint.pos.y;
        this.endPoint.x = endPoint.pos.x;
        this.endPoint.y = endPoint.pos.y;
        // let wayBool = this.checkedLists.some((item) => item == "2");
        // if (wayBool) {
        let f = new Feature({
          geometry: new LineString([
            [this.startPoint.x, this.startPoint.y],
            [this.endPoint.x, this.endPoint.y],
          ]),
        });
        let source = new VectorSource();
        source.addFeature(f);
        let layer = new VectorLayer({
          source: source,
          visible: true,
          name: "线条",
          className: "normalPoints",
        });
        this.map.addLayer(layer);
        // }
      }
      // });
    },
    checkboxChang(item) {
      let mapBool = this.checkedLists.some((item) => item == "1");
      this.siteBool = this.checkedLists.some((item) => item == "3");
      this.inspectionBool = this.checkedLists.some((item) => item == "4");
      this.changeBool = this.checkedLists.some((item) => item == "5");
      this.robotBool = this.checkedLists.some((item) => item == "6");
      //地图显隐
      if (mapBool) {
        this.WebGLPointsLayer.setVisible(true);
      } else {
        this.WebGLPointsLayer.setVisible(false);
      }
    },
    //控制图标显隐
    showPoint(pointBoolean, id) {
      if (pointBoolean === "1") {
        this.map
          .getOverlays()
          .getArray()
          .forEach((item) => {
            let ele = item.getElement();
            let itemId = ele.getAttribute("id");
            if (itemId.includes(id)) {
              item.setPosition([
                item.options.position[0],
                item.options.position[1],
              ]);
            }
          });
      } else {
        this.map
          .getOverlays()
          .getArray()
          .forEach((item) => {
            let ele = item.getElement();
            let itemId = ele.getAttribute("id");
            if (itemId.includes(id)) {
              item.setPosition(undefined);
            }
          });
      }
    },
    /**数组去重 */
    unique(arr1) {
      const res = new Map();
      return arr1.filter(
        (a) => !res.has(a.locationPos) && res.set(a.locationPos, 1)
      );
    },
  },
  destroyed() {
    //清除设备定时器
    clearInterval(this.runmodelTimer);
    clearInterval(this.time);
    this.runmodelTimer = null;
    this.time = null;
  },
};
</script>
<style lang="scss" scoped>
.canvan-p {
  position: relative;
  transform: translate(0, 0);
  display: flex;
  justify-content: center;
  align-content: center;
}
.left-top,
.right-top {
  position: fixed;
  padding: 3px 10px;
  box-sizing: border-box;
  background-color: rgba(255, 255, 255, 0.15);
  z-index: 2000;
}
// 左下
// 左上
.left-top {
  display: flex;
  flex-direction: column;
  width: 40px;
  height: 88px;
  position: absolute;
  left: 16px;
  top: 16px;
  color: red;
  z-index: 9000;
  div {
    flex: 1;
    display: flex;
    align-items: center;
  }
  div:nth-child(2) {
    border-top: 1px solid rgba(241, 243, 249, 0.2);
  }
  img {
    width: 20px;
    height: 20px;
  }
}
// 右上
.right-top {
  width: 116px;
  height: 216px;
  position: absolute;
  right: 16px;
  top: 46px;
  color: red;
}
.right-top-img {
  width: 20px;
  height: 20px;
  vertical-align: middle;
}
.mar-l-5 {
  margin-left: 5px;
}
.mar-l-10 {
  margin-left: 10px;
}

// 左下
.left-bottom {
  position: absolute;
  left: 16px;
  bottom: 16px;
  display: flex;
  z-index: 9999;
  .one {
    margin-right: 15px;
    .percent {
      .per-txt {
        width: 60px;
        text-align: center;
      }
      .border {
        width: 60px;
        height: 8px;
        border: 1px solid rgba(255, 255, 255, 1);
        border-top: 0;
      }
    }
  }
  .two {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 32px;
    // padding-left: 15px;
    // border-left: 1px solid rgba(255, 255, 255, 1);
    img {
      width: 20px;
      height: 20px;
      vertical-align: middle;
    }
  }
}
// 右下
.right-bottom {
  position: absolute;
  display: flex;
  right: 16px;
  bottom: 16px;
  color: red;
  z-index: 9000;
  .one,
  .two,
  .three {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    box-sizing: border-box;
    background-color: rgba(255, 255, 255, 0.15);
    img {
      width: 20px;
      height: 20px;
      vertical-align: middle;
    }
  }
  .one {
    display: flex;
    width: 81px;
    height: 40px;
    padding: 0;
    div {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    div:nth-child(1) {
      border-right: 1px solid rgba(241, 243, 249, 0.2);
    }
  }
  .two {
    width: 40px;
    height: 40px;
    margin: 0 16px;
  }
  .three {
    width: 40px;
    height: 40px;
  }
}
.bgImgDiv {
  background: #263440;
  .bgHeader {
    padding: 10px;
    background: #33414c;
    .actionImg {
      display: inline-block;
      float: right;
    }
  }
  .bgContent {
    padding: 12px;
    .tip-grey {
      color: #a6acb1;
      font-size: 12px;
    }
    .tip-red {
      color: #ff4c5e;
      font-size: 12px;
    }
    .tipsDiv {
      margin-top: 8px;
    }
    .status-btn {
      display: inline-block;
      width: 86px;
      height: 28px;
      line-height: 28px;
      border-radius: 2px;
      opacity: 0.7;
      border: 1px solid #00d1ff;
      background-color: #1e5366;
      color: #ffff;
      padding-left: 28px;
    }
  }
}
.actionButton {
  display: inline-block;
  color: #00d1ff;
  border-bottom: 1px solid #00d1ff;
  cursor: pointer;
  position: absolute;
  right: 12px;
}
.pickup-cursor {
  cursor: default;
  // cursor: url("../../assets/images/home/pickup.png"), auto;
}
.pickup-default {
  cursor: default;
}
.imgTitle {
  display: inline-block;
  width: 100px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: middle;
  text-align: right;
  position: absolute;
  right: 0;
  top: 57px;
}
::v-deep {
  .setCoordinate {
    .el-input__inner {
      background-color: #12222f;
      border-radius: 2px;
      border: 1px solid #33414c;
      height: 28px;
      line-height: 28px;
      padding-left: 0;
      padding-right: 0;
    }
    .el-input-number__decrease {
      display: none;
    }
    .el-input-number__increase {
      display: none;
    }
  }
}
::v-deep {
  .normalPoints {
    z-index: 999999 !important;
  }
}
::v-deep {
  .el-checkbox-group {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}
::v-deep {
  .ol-full-screen {
    right: 1em;
    // top: 27.5em;
  }
}
::v-deep {
  .el-collapse-item__header {
    background: #263440;
    color: #ffff;
    border-bottom: none;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
  }
  .el-collapse-item__content {
    background: #263440;
    padding-bottom: 10px;
  }
  .el-collapse-item__wrap {
    border-bottom: 1px dashed #33414c;
    background-color: inherit;
  }
  .el-collapse {
    border-bottom: 1px dashed #33414c;
    border-top: 1px dashed #33414c;
  }
}
</style>
<style>
.newheel-setBg {
  padding: 0;
  z-index: 9999 !important;
}
input[type="file"] {
  color: transparent;
}
</style>
